/*竞赛项目类型设置 */
<template>
  <div>
      <condition-card @reset="resetSearch" @search="onSearch" label-position="right" label-width="150px" >
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="8">
            <el-form-item :label="$t('expertGroupSett.competition')">
              <el-select v-model="queryForm.condition.name">
                <el-option v-for="item in options.degreeType" :key='item.key' :value="item.value" :label="item.label"></el-option>
              </el-select>
              <!-- <el-input v-model.trim="queryForm.condition.name" style="width:100%"></el-input> -->
            </el-form-item>
          </el-col>
          
        </el-row>
      </condition-card>
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('expertGroupSett.projectList')}}</h1>
          <div class="edu-opertion-bar sub-title">
            <el-row type="flex" class="row-bg" justify="space-between">
            <h1 style="font-size: 15px">{{$t('expertGroupSett.residual')}}{{Math.round((100-total)*100)/100}}%</h1>
            <div class="float-right" style="display: flex;">
              <el-button type="primary" style="margin-left:10px" @click="increased">{{$t('expertGroupSett.increased')}}</el-button>
              <el-button type="primary" style="margin-left:10px" :disabled="this.dataList.length==0" @click="compile">{{$t('expertGroupSett.compile')}}</el-button>
            </div>
            </el-row>
          </div>
        <edu-table :pagination="false" :selection='false' :orderFixed='false'  :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <edu-table-column :label="$t('expertGroupSett.competition')" prop="name"></edu-table-column>
          <edu-table-column :label="$t('expertGroupSett.propor')" prop="percent"></edu-table-column>
          <edu-table-column :label="$t('expertGroupSett.budget')" prop="budgetMoney"> </edu-table-column>
          <edu-table-column :label="$t('expertGroupSett.competitionType')" prop="remark"> </edu-table-column>
          <edu-table-column :label="$t('common.text.operation')" fit prop="operate">
            <template slot-scope="props">
              <el-button type="text" @click="examineDelete(props.row)">{{$t('expertGroupSett.delete')}}</el-button>
            </template>
          </edu-table-column>
          
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryForm.pageNum_"
                :page-sizes="[20, 40, 80, 100]"
                :page-size="queryForm.pageSize_"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryForm.total_"
                style="float:right;margin-top:10px"
              ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
      <el-dialog
        :title="$t('expertGroupSett.addCompetition')"
        :visible.sync="dialogVisible"
        :close-on-click-modal='false'
        width="40%"
        :before-close="handleClose">
        <el-form :model="requeryForm" ref='requeryForm' :rules="rules" label-width="141px" label-suffix="：">
          <el-form-item :label="$t('expertGroupSett.competition')" prop="name">
            <el-input v-model.trim="requeryForm.name" style="width:70%" maxlength="64"></el-input>
          </el-form-item>
          <el-form-item :label="$t('expertGroupSett.competitionType')" prop="remark">
            <el-input v-model.trim="requeryForm.remark" type="textarea" :rows="3" maxlength="64" style="width:70%"></el-input>
          </el-form-item>
          <el-form-item :label="$t('expertGroupSett.proportion')" prop="percent">
            <!-- @change="validateWeight" @change="validateWeight($event)"-->
            <el-input v-model="requeryForm.percent"   maxlength="5" style="width:70%"></el-input>%
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <!-- <el-button @click="cancel">取消</el-button> -->
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="$t('expertGroupSett.editCompetition')"
        :visible.sync="dialogVisibleEdit"
        :close-on-click-modal='false'
        width="40%"
        :before-close="handleCloseEdit">
        <el-form :model="requeryFormEdit" ref='requeryFormEdit' :rules="rulesEdit" label-width="140px" label-suffix="：">
          <h1 style="font-size: 15px">{{$t('expertGroupSett.residual')}}{{100-totalEdit >=0?Math.round((100-totalEdit)*100)/100:0}}%</h1>
          <edu-table
            :pagination="false"
            :order="false"
            :selection="false"
            :tooltipEffect="tooltipEffect"
            stripe
            :data="requeryFormEdit.studentList"
            size="mini" >
            <edu-table-column :label="$t('expertGroupSett.competition')" prop="name" >
            </edu-table-column>
            <edu-table-column :label="$t('expertGroupSett.propor')" prop="percent" >
              <template slot-scope="scope">
                  <el-form-item style="margin-top: 15px;"
                      :prop="'studentList.' + scope.$index + '.percent'"
                      label-width="0"
                      :rules="rulesEdit.percent"
                  >
                      <el-input v-model.trim="scope.row.percent" @change="WeightEdit(scope.row, scope.$index)" maxlength="5"></el-input>
                  </el-form-item>
              </template>
            </edu-table-column>
            <edu-table-column :label="$t('expertGroupSett.budget')" prop="budgetMoney" >
            </edu-table-column>
          </edu-table>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCloseEdit">取消</el-button>
          <!-- <el-button @click="cancel">取消</el-button> -->
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </el-dialog>
  </div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import competiManagementApi from 'common/src/api/subjectCompetition/competiManagement';
export default {
  
  data() {
    let cannotEnter = (rule, value, callback) => {
        let reg = /[`$]/im
        if (reg.test(value)) {
            return callback(new Error(this.$t('identificationToDoList.cannotContain')))
        } else if (value === '') {
            return callback(new Error(this.$t('internship.pleaseEnter')))
        }
        return callback()
    }
    let validateWeight = (rule, value, callback) => {
      if (value == '' || value == null) {
        return callback()
      }
      if (value == 0) {
        return callback(new Error(this.$t('expertGroupSett.decimalPlace')))
      } 
      if (value <= 100 && value > 0) {
        let expReg = /^\d{1,3}$|^\d{1,2}[.]\d{1,2}$/;
        if (!expReg.test(value)) {
          return callback(new Error(this.$t('expertGroupSett.decimalPlace')))
        } else {
          return callback()
        }
      } else {
        return callback(new Error(this.$t('expertGroupSett.decimalPlace')))
      }
    }
    return {
      requeryForm: {
        name: '',
        remark: '',
        percent: null
      },
      requeryFormEdit: {
        studentList: []
      },
      // requeryFormEdit: {},
      rulesEdit: {
        percent: [{ validator: this.validateWeightEdit, trigger: 'change' }],
      },
      rules: {
        percent: [{ validator: validateWeight, trigger: 'change' }],
        name: [{ required: true, validator: cannotEnter, trigger: 'blur' }],
        remark: [{ required: true, validator: cannotEnter, trigger: 'blur' }]
      },
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          name: ''
        }
      },
      dialogVisibleEdit: false,
      dialogVisible: false,
      indexKey: 1,
      total: 0,
      totalEdit: 0,
      dataList: [],
      multipleSelection: [],
      options: {
        TrainingLevel: [],
        degreeType: [],
        formLearning: [],
        faculty: [],
        profession: [],
        trainingCategory: []
      },
    };
  },
  created() {
    this.getOptions()
  },
  mounted() {
    this.postListPage(this.queryForm)
  },
  methods: {
    postListPage(data) {
      this.total = 0
      this.options.degreeType = []
      competiManagementApi.projectcategoryListPage(data).then(res => {
        this.dataList = res.data.list
        if (this.dataList) {
          this.dataList.forEach(el => {
            this.total += el.percent
            this.options.degreeType.push({
              label: el.name,
              value: el.name
            })
          })
        }
        this.queryForm.total_ = res.data.total_
      })
    },
    // 字典获取
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_PYCC", 'X_PYLB', 'X_XWLX', 'X_XXXS', 'X_YX']
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            trainingCategory: "X_PYLB",
            // degreeType: "X_XWLX",
            formLearning: "X_XXXS",
            faculty: "X_YX",
            TrainingLevel: "X_PYCC"
          },
          res.data,
          this.options
        );
      });
    },
    // validateWeight(rule, value, callback) {
    //   console.log(value, 'kong', rule);
    //   if (value == 0) {
    //     return callback(new Error(this.$t('expertGroupSett.decimalPlace')))
    //   } else if (value <= 100 && value > 0) {
    //     console.log(value, 'kong2');
    //     let expReg = /^\d{1,3}$|^\d{1,2}[.]\d{1,2}$/;
    //     if (!expReg.test(value)) {
    //        console.log(value, 'kong3');
    //       return callback(new Error(this.$t('expertGroupSett.decimalPlace')))
    //     } else {
    //       return callback()
    //     }
    //   } else if(!value) {
    //     console.log(value, 'kong1');
    //     return callback()
    //   } 
    // },
    validateWeightEdit(rule, value, callback) {
      if (value <= 100 && value>0) {
          let expReg = /^([1-9][0-9]*)(\.\d{1,2})?$/
          if (!expReg.test(value)) {
            callback(new Error(this.$t('expertGroupSett.pleaseNumber')))
          } else {
            callback()
          }
      } else if (value == '' || value == null) {
        callback(new Error(this.$t('internship.pleaseEnter')))
      } else {
        callback(new Error(this.$t('expertGroupSett.decimalPlace')))
      }
    },
    WeightEdit(data, index) {
      this.totalEdit = 0
      this.requeryFormEdit.studentList[index].percent = Math.round(data.percent*100)/100 || null
      this.requeryFormEdit.studentList.forEach(el => {
        if (this.totalEdit <=100) {
          this.totalEdit += el.percent
        }
      })
      if (data.percent>0) {
        let num = data.budget * (data.percent)/100
        this.requeryFormEdit.studentList[index].budgetMoney = Math.round(num*100)/100
      }
    },
    // 删除
    examineDelete(data) {
      this.$delConfirm().then(() => {
        competiManagementApi.projectcategoryRemoveById(data.id).then(res => {
          this.$message(this.$t('internship.successfully'));
          this.queryForm.pageNum_ = 1;
          this.postListPage(this.queryForm)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('internship.cancelOpera')
        });  
      });
      
    },
    // 查询
    onSearch() {
      this.queryForm.pageNum_ = 1
      this.postListPage(this.queryForm)
    },
    // 重置
    resetSearch() {
      for (let key in this.queryForm.condition) {
        this.queryForm.condition[key] = '';
      }
      this.queryForm.pageNum_ = 1
      this.postListPage(this.queryForm)
    },
    // 弹框关闭
    handleClose() {
      this.dialogVisible = false
      for (let key in this.requeryForm) {
        this.requeryForm[key] = '';
      }
      this.$refs['requeryForm'].resetFields();
    },
    handleCloseEdit() {
      this.dialogVisibleEdit = false
      this.requeryFormEdit.studentList = []
      this.$refs['requeryFormEdit'].resetFields();
    },
    // 弹框关闭
    // // 弹框确定
    // cancel() {
    //   this.dialogVisible = false
    //   this.$refs['requeryForm'].resetFields();
    // },
    confirm() {
      this.$refs['requeryForm'].validate(valid => {
        if (valid) {
          competiManagementApi.projectcategoryAdd(this.requeryForm).then(res => {
            this.dialogVisible = false
            this.$message.success(this.$t('internship.successfully'));
            this.queryForm.pageNum_ = 1;
            this.postListPage(this.queryForm)
            for (let key in this.requeryForm) {
              this.requeryForm[key] = '';
            }
            this.$refs['requeryForm'].resetFields();
          })
        }
      })
    },
    confirmEdit() {
      this.$refs['requeryFormEdit'].validate(valid => {
        if (valid) {
          if (100-this.totalEdit<0) {
            return this.$message.error(this.$t('expertGroupSett.budgetedAmount'));
          }
          competiManagementApi.projectcategoryModify(this.requeryFormEdit.studentList).then(res => {
            this.$message.success(this.$t('internship.successfully'));
            this.queryForm.pageNum_ = 1;
            this.postListPage(this.queryForm)
            this.handleCloseEdit()
          })
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 新增
    increased() {
      this.dialogVisible = true
    },
    // 编辑
    compile() {
      let data = {
        pageNum_: 1,
        pageSize_: 999,
        total_: 0,
        condition: {
          name: ''
        }
      }
      this.totalEdit = 0
      competiManagementApi.projectcategoryListPage(data).then(res => {
        // if (res.data.list.length > 0) {

          this.requeryFormEdit.studentList = res.data.list
          if (this.requeryFormEdit.studentList) {
            this.requeryFormEdit.studentList.forEach(el => {
              this.totalEdit += el.percent
            })
          }
          this.queryForm.total_ = res.data.total_
          this.dialogVisibleEdit = true
        // } else {
        //   this.$message('')
        // }
      })
      
      // this.multipleSelection
    },
    changeExam() {
      this.indexKey = 1
    },
    // 分页
    handleSizeChange(val) {
      this.queryForm.pageNum_ = 1
      this.queryForm.pageSize_ = val
      this.postListPage(this.queryForm)
    },
    // 分页
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.postListPage(this.queryForm)
    },
  }
}
</script>
<style  scoped>

</style>